<template>
  <main-box>
    <PlusSearch
      v-model="queryform"
      :columns="formConfig"
      :show-number="2"
      label-width="80"
      label-position="right"
      class="mb-xs"
      @search="initData()"
      @reset="handleRest()"
    >
      <template #plus-field-warehouseId>
        <k-select-http
          v-model="queryform.warehouseId"
          paramsKey="searchValue"
          :immediately="true"
          :httpfn="getWarehouseList"
          placeholder="请选择工具室"
          :keyprops="{ label: 'name', value: 'warehouseId' }"
        />
      </template>
      <template #plus-field-noReturnType>
        <el-radio-group v-model="queryform.noReturnType">
          <el-radio-button label="全部" :value="-1" />
          <el-radio-button label="异常" :value="2" />
          <el-radio-button label="超时" :value="3" />
        </el-radio-group> </template
    ></PlusSearch>
    <div class="mb-2">
      <btnExport
        :exportApi="exportApi"
        :queryform="getQueryParam()"
        download-name="未归还记录"
      />
    </div>
    <PureTable
      ref="tableRef"
      border
      adaptive
      :loading="loading"
      :data="tableData"
      :columns="columns"
      :pagination="pagination"
      @page-size-change="initData()"
      @page-current-change="initData(false)"
    />

    <detail-info ref="detailInfoRef" />
  </main-box>
</template>
<script setup lang="tsx">
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { useTableConfig } from "@/utils/tableConfig";
import { type PlusColumn, PlusSearch } from "plus-pro-components";
import { diffDate } from "@/utils";

import { listApi } from "@/api/record/unReturn";
import { exportApi } from "@/api/record/list";

import kSelectHttp from "@/components/k-select-http/index.vue";
import { allListApi as getWarehouseList } from "@/api/warehouse";
import btnExport from "@/components/btnExport/index.vue";

import detailInfo from "../list/modules/detail-info.vue";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";

const router = useRouter();
/* 查询表单 */
const formConfig: PlusColumn[] = [
  {
    label: "借出时间",
    prop: "time",
    valueType: "date-picker",
    fieldProps: {
      type: "daterange",
      valueFormat: "YYYY-MM-DD"
    }
  },
  {
    label: "事件类型",
    prop: "noReturnType"
  },
  {
    label: "工具室",
    prop: "warehouseId"
  },
  {
    label: "查询",
    prop: "searchValue",
    fieldProps: {
      placeholder: "物品名称/编号/分类/型号/用户"
    }
  }
];
const queryform = ref({
  time: [],
  noReturnType: -1,
  searchValue: "",
  warehouseId: ""
});

const handleRest = () => {
  initData(true);
  queryform.value.noReturnType = -1;
};

/* 表格数据 */
const { pagination } = useTableConfig();
const tableData = ref([]);
const loading = ref(false);
const columns = [
  {
    label: "物件图片",
    prop: "picUrl",
    cellRenderer: ({ row }) => {
      const { picUrl } = row.tool;
      let list = [];
      if (picUrl) {
        list = picUrl.split(",");
      }
      return list.map((item, index) => {
        return (
          <el-image
            src={item}
            width={50}
            initial-index={index}
            preview-src-list={list}
            preview-teleported={true}
          />
        );
      });
    }
  },
  { label: "物件编号", prop: "tool.code" },
  { label: "物件名称", prop: "tool.name" },
  { label: "物件型号", prop: "tool.modelName" },
  { label: "标签编号", prop: "tool.labelCode" },
  { label: "工具室", prop: "tool.warehouseName" },
  { label: "存放位置", prop: "tool.storageLocation" },
  { label: "借出时间", prop: "lendTime" },
  {
    label: "用户",
    prop: "nickName",
    formatter: ({ nickName, userName }) => nickName ?? userName
  },
  {
    label: "未归还类型",
    prop: "noReturnType",
    cellRenderer: ({ row }) => {
      const type = {
        1: { col: "success", text: "正常借出" },
        2: { col: "danger", text: "异常归还" },
        3: { col: "primary", text: "超期未归还" }
      };
      const temp = type[row.noReturnType];
      return <el-tag type={temp.col}>{temp.text}</el-tag>;
    }
  },
  {
    label: "使用时长",
    prop: "useTime",
    width: 180,
    cellRenderer: ({ row }) => {
      // 未归还:当前时间-借出时间 0
      // 己归还: 归还时间 - 借出时间 1
      const { isReturn, lendTime, returnTime, useState } = row;
      const col = useState == 2 ? "danger" : "default";
      const text = diffDate(lendTime, Number(isReturn) ? returnTime : null);
      return (
        <el-link type={col} underline={false}>
          {text}
        </el-link>
      );
    }
  },
  { label: "借出期限(小时)", prop: "tool.maxLendTime" },
  {
    label: "操作",
    prop: "action",
    fixed: "right",
    width: 140,
    cellRenderer: ({ row }) => {
      return (
        <div class="btn-link">
          <el-link
            type="primary"
            underline={false}
            onClick={() => handleDetail(row)}
          >
            查看
          </el-link>
          <el-link
            type="success"
            underline={false}
            onClick={() => goDetail(row)}
          >
            工具详情
          </el-link>
        </div>
      );
    }
  }
];
/* 导出参数 */
const getQueryParam = () => {
  const params = {
    ...queryform.value,
    isReturn: 0
  } as any;
  if (queryform.value.noReturnType == -1) {
    delete params.noReturnType;
  }
  if (params.time && params.time.length) {
    params.params = {
      startTime: params.time[0],
      endTime: params.time[1]
    };
  }
  delete params.time;
  return params;
};
const initData = async (needInit = true) => {
  loading.value = true;
  if (needInit) {
    pagination.currentPage = 1;
  }
  const params = {
    pageNum: pagination.currentPage,
    pageSize: pagination.pageSize,
    ...getQueryParam()
  } as any;

  await listApi(params).then(res => {
    tableData.value = [...res.rows];
    pagination.total = Number(res.total);
  });
  loading.value = false;
};
initData();

/* 操作 */
const detailInfoRef = ref<any>();
const handleDetail = row => {
  detailInfoRef.value.show(row);
};
const goDetail = row => {
  const query = {
    path: "/tool/detail",
    query: { id: String(row.tool.toolId) },
    name: "ToolDetailIndex"
  };
  useMultiTagsStoreHook().handleTags("push", {
    ...query,
    meta: {
      title: "工具详情",
      dynamicLevel: 1
    }
  });
  router.push(query);
};
</script>
